# -*- coding:utf-8 -*- #

# ----------------------------------------------------------
# Name:        server
# Description:
# Authon:      syl
# Date:        2020-12-09
# ----------------------------------------------------------


import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import time
from tornado import gen
from tornado.concurrent import run_on_executor, Future
from concurrent.futures import ThreadPoolExecutor
from tornado.options import define, options
import json


define("port", default=6001, help="run on the given port", type=int)


class BaseHandler(tornado.web.RequestHandler):
    def send(self, obj):
        self.write(obj)


class TestHandler(BaseHandler):
    """
    多线程 异步非阻塞
    """
    max_thread_num = 100
    executor = ThreadPoolExecutor(max_workers=max_thread_num)

    @run_on_executor
    def my_func(self, *args, **kwargs):
        p = args[0]
        time.sleep(10)
        return p


    @gen.coroutine
    def post(self, args=None):
        params = self.request.body
        params = json.loads(params)
        res = yield self.my_func(params)
        self.send({"msg": "接收成功", "success": True, 'res': res})
        self.finish()


class Test2Handler(BaseHandler):
    """单线程 异步非阻塞"""
    def dosomework(self, p):
        time.sleep(10)
        print(p)
        self.send(p)
        self.finish()

    @gen.coroutine
    def post(self):
        params = self.request.body
        params = json.loads(params)
        f = Future()
        f.add_done_callback(self.dosomework(params))
        yield f


class Test3Handler(BaseHandler):
    """同步阻塞"""
    def post(self):
        params = self.request.body
        params = json.loads(params)
        print(params)
        time.sleep(10)
        self.send(params)


def getPoints():
    handlers = []
    handlers.extend({
        (r'/api/test', TestHandler),
        (r'/api/test2', Test2Handler),
        (r'/api/test3', Test3Handler),
    })
    return handlers


if __name__ == "__main__":
    tornado.options.parse_command_line()
    points = getPoints()
    app = tornado.web.Application(handlers=points)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(options.port)
    http_server.start()
    tornado.ioloop.IOLoop.instance().start()